package control;

import java.io.File;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;

import dao.ItemData;
/**
 * Servlet implementation class AddItem
 */
public class AddItem extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddItem() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String avatarFolder = getServletContext().getRealPath("image\\avatarItem");
		MultipartRequest mtr = new MultipartRequest(request, avatarFolder, 5*1024*1024,"UTF-8");
		String nameItem = mtr.getParameter("nameItem");
		String priceItem = mtr.getParameter("priceItem");
		String avatarItem = mtr.getFile("avatarItem").getName();
		long idItem = System.currentTimeMillis();
		String err = "";
		String avatarPath ="";
		if (mtr.getFile("avatarItem") != null) {
			String avatarName = mtr.getFile("avatarItem").getName();
			 avatarPath = avatarFolder + "\\" + avatarName;
			
			File f = new File(avatarPath);
			File f_new = new File(avatarFolder + "\\" + idItem + ".png");
			f.renameTo(f_new);
		}
		System.out.println(priceItem+"  tien");
		System.out.println(nameItem + "   k co j");
		System.out.println(avatarFolder);
		System.out.println(avatarItem+"  avater");
		if(nameItem.equals("")||priceItem.equals("")||avatarItem.equals("")){
		}
		String url = "/confirm.jsp";
		if(err.length()>0){
			url = "/addItem.jsp";
			request.setAttribute("err", err);
			
		}
		
		if(err.equals("")){
			double price = Double.parseDouble(priceItem);
			avatarPath="image/avatarItem/"+idItem+".png";
			ItemData.addItem(idItem, nameItem, price, avatarPath);
		}
		RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
		rd.forward(request, response);
	}

}
